package com.example.apricots.Utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.TypedValue;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.example.apricots.R;

/**
 * 继承自AppCompatImageView圆形头像工具
 */
public class DiyImageViewCircle extends AppCompatImageView{
    private static final int DEFAULT_RADIUS = 100;  //默认的半径,dp
    private int radius = dp2px(DEFAULT_RADIUS);

    //将dp单位转换为px
    private int dp2px(int defaultRadius) {
        float v = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                defaultRadius,
                getResources().getDisplayMetrics());
        return (int)v;
    }

    public DiyImageViewCircle(@NonNull Context context) {
        super(context,null);
    }

    public DiyImageViewCircle(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs,0);
    }

    public DiyImageViewCircle(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取属性值----------------------

        //得到MyImageView
        TypedArray typedArray = getContext().obtainStyledAttributes(
                attrs, R.styleable.DiyImageViewCircle
        );
        //取出MyImageView_radius属性所对应的数据
        radius = (int) typedArray.getDimension(R.styleable.DiyImageViewCircle_radius, radius);
        typedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getWidth(); //得到宽度
        int height = getHeight();   //得到高度

        /*int radius = Math.min(width, height) / 3;   //计算半径 */

        Path path = new Path(); //定义圆形路径

        //圆心,半径,顺时针
        path.addCircle(width/2,height/2,radius,Path.Direction.CW);

        canvas.save();  //保存画布设置
        canvas.clipPath(path);  //裁切画布的可绘制区域
        super.onDraw(canvas);   //调用父类的画图方法
        canvas.restore();
    }
}
